package service

import (
	"publish-manage/internal/model"
	"publish-manage/internal/ws"
	"publish-manage/pkg/database"
	"publish-manage/pkg/util"
)

var ManagePublishService = new(managePublishService)

type managePublishService struct{}

func (s *managePublishService) Publish(file string, appPackage *model.AppPackage, agentIds ...string) error {
	if err := s.saveInfo(file, appPackage); err != nil {
		return err
	}

	// 获取要部署的代理
	var agentPackageList []*model.AgentPackage
	if err := database.DB.Find(&agentPackageList, &model.AgentPackage{PackageId: appPackage.Id}); err != nil {
		return err
	}
	var publishAgentIds []string
	if len(agentIds) > 0 {
		// 指定了代理服务id，进行检查是否在部署包列表中
		for i := 0; i < len(agentPackageList); i++ {
			id := agentPackageList[i].Id
			for j := 0; j < len(agentIds); j++ {
				if id == agentIds[j] {
					publishAgentIds = append(publishAgentIds, id)
					break
				}
			}
		}
	}

	go ws.AgentManager.NotifyAgents(appPackage.Id, publishAgentIds...)
	return nil
}

func (_ *managePublishService) saveInfo(file string, appPackage *model.AppPackage) error {
	session := database.DB.NewSession()
	defer session.Close()
	session.Begin()

	// 保存部署包版本信息
	if _, err := session.Insert(&model.PackageVersion{
		Id:        util.GenerateDatabaseID(),
		AppId:     appPackage.AppId,
		PackageId: appPackage.Id,
		Path:      file,
	}); err != nil {
		return err
	}

	if err := session.Commit(); err != nil {
		return err
	}
	return nil
}
